<template>
  <div class="goods-type">
    <div class="goods-type__body">
      <div class="left">
        <el-tree
          v-loading="typeLoading"
          :data="list"
          :props="treeProps"
          :expand-on-click-node="false"
          highlight-current
          node-key="id"
          @node-click="handleNodeClick"
        >
          <template v-slot="{ node, data }">
            <div class="custom-tree-node">
              <div :title="data.name" class="type-name">{{ data.name }}</div>
              <el-dropdown @command="handleDropdownClick($event, data)">
                <div
                  v-show="data.id === currentNode"
                  class="custom-tree-node-button"
                >
                  <i class="el-icon-more" />
                </div>
                <template #dropdown>
                  <el-dropdown-menu v-if="!data?.goods_type_id">
                    <el-dropdown-item command="edit">编辑</el-dropdown-item>
                    <el-dropdown-item command="remove">删除</el-dropdown-item>
                    <el-dropdown-item command="createGoods">物品录入</el-dropdown-item>
                  </el-dropdown-menu>

                  <el-dropdown-menu v-else>
                    <el-dropdown-item command="goodsRemove">删除</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </el-tree>

        <div class="left__add-button">
          <el-button type="text" icon="el-icon-plus" @click="handleOpenCreateGoodsTypeDialog">
            新建类型
          </el-button>
        </div>
      </div>

      <div class="line">
        <el-divider direction="vertical" style="margin: 0;" />
      </div>

      <div class="right">
        <div v-if="currentGood" class="right__details-content">
          <template v-if="currentGood && !loading">
            <Form
              v-if="currentGood"
              ref="formRef"
              :model="formModel"
              :goods-type-list="list"
              :disabled="disabled"
            />

            <div class="button-group">
              <template v-if="isEdit">
                <el-button @click="handleCancel">取消</el-button>
                <el-button
                  type="primary"
                  :loading="btnLoading"
                  @click="handleEditConfirm"
                >
                  确定
                </el-button>
              </template>

              <template v-else>
                <el-button v-if="formModel.is_directory === 0" type="primary" @click="handleOpenUnitDialog">辅助单位</el-button>
                <el-button type="primary" @click="handleEditGoodsType">编辑</el-button>
              </template>

            </div>
          </template>
          <div
            v-else
            v-loading="loading"
            style="width: 100%; height: 100%;"
          />
        </div>

        <div v-else>
          <el-empty description="点击左侧分类查看详情" />
        </div>
      </div>
    </div>

    <CreateGoodsDialog
      ref="dialogRef"
      :visible.sync="showDialog"
      :goods-type-list="list"
      :loading="createLoading"
      @confirm="handleConfirm"
    />

    <EditAuxiliaryUnitDialog
      :visible.sync="showEditUnitDialog"
      :unit-list="unitList"
      @confirm="editUnitConfirm"
    />

    <CreateGoodsTypeDialog
      ref="createGoodsDialogRef"
      :visible.sync="showCreateGoodsTypeDialog"
      :loading="createLoading"
      @confirm="handleCreateGoodsTypeConfirm"
    />

    <EditGoodsTypeDialog
      :visible.sync="showEditGoodsTypeDialog"
      :loading="createLoading"
      :model="goodsTypeModel"
      @confirm="handleEditGoodsTypeConfirm"
    />
  </div>
</template>
<script>
import {
  createGoodsType,
  createWarehouseWarrant,
  deleteGoodsType, deleteWarehouseWarrant,
  editGoodsType,
  editWarehouseWarrant,
  getGoodsType
} from '@/api/officeSuppliesManagement'
import { cloneDeep } from 'lodash-es'
import Form from './components/Form.vue'
import CreateGoodsDialog from '@/views/officeSuppliesManagement/components/CreateGoodsDialog.vue'
import { sleep } from '@/utils'
import EditAuxiliaryUnitDialog from '@/views/officeSuppliesManagement/components/EditAuxiliaryUnitDialog.vue'
import CreateGoodsTypeDialog from '@/views/officeSuppliesManagement/components/CreateGoodsTypeDialog.vue'
import EditGoodsTypeDialog from '@/views/officeSuppliesManagement/components/EditGoodsTypeDialog.vue'
export default {
  name: '',
  components: {
    Form,
    CreateGoodsDialog,
    EditAuxiliaryUnitDialog,
    CreateGoodsTypeDialog,
    EditGoodsTypeDialog
  },
  data() {
    return {
      list: [],
      treeProps: {
        label: 'name',
        children: 'goods'
      },
      currentNode: null,
      goodsTypeDetails: null,
      formModel: {
        name: '',
        remark: '',
        unit: '',
        unitList: []
      },
      formModelBackup: {},
      disabled: true,
      loading: false,
      btnLoading: false,
      showDialog: false,
      createLoading: false,
      showEditUnitDialog: false,
      unitList: [],
      showCreateGoodsTypeDialog: false,
      showEditGoodsTypeDialog: false,
      goodsTypeModel: {
        name: '',
        remark: ''
      },
      currentGood: null,
      typeLoading: false
    }
  },
  computed: {
    isEdit() {
      return !this.disabled
    }
  },
  created() {
    this.getGoodsType()
  },
  methods: {
    handleNodeClick(data, node) {
      this.currentNode = data.id
      if (data.goods_type_id) {
        // this.currentGood = data.id
        this.goodsEdit(data)
      }
    },

    handleDropdownClick(e) {
      switch (e) {
        case 'edit':
          this.editGoodsTypes()
          break

        case 'remove':
          this.removeGoodsType()
          break

        case 'createGoods':
          this.createGoods()
          break

        case 'goodsRemove':
          this.goodsRemove()
          break

        default:
          return
      }
    },

    // ----------------------------- Goods Type Begin -----------------------------------
    async getGoodsType() {
      this.typeLoading = true
      try {
        const res = await getGoodsType()
        this.list = res.data
      } catch (error) {
        this.$message.error(error?.response?.data?.message || '物品类型获取失败')
      } finally {
        await this.sleep(500)
        this.typeLoading = false
      }
    },

    editGoodsTypes() {
      const target = this.list.find(item => item.id === this.currentNode)
      this.goodsTypeModel.name = target?.name
      this.goodsTypeModel.remark = target?.remark
      this.showEditGoodsTypeDialog = true
    },

    removeGoodsType() {
      this.$confirm(
        '是否删除该项分类？',
        {
          type: 'warning',
          confirmButtonText: '删除',
          cancelButtonText: '取消'
        }
      ).then(() => {
        this.deleteGoodsTypeFetcher(this.currentNode)
      })
    },

    handleOpenCreateGoodsTypeDialog() {
      this.showCreateGoodsTypeDialog = true
      this.$nextTick(() => {
        this.$refs.createGoodsDialogRef.resetFields()
      })
    },

    async handleCreateGoodsTypeConfirm(e) {
      await this.createGoodsType(e)
      this.refresh()
    },

    async createGoodsType(data) {
      this.createLoading = true
      try {
        await createGoodsType(data)
        this.$message.success('创建成功')
        this.showCreateGoodsTypeDialog = false
      } catch (error) {
        this.$message.error(error?.response?.data?.message || '创建失败')
      } finally {
        await this.sleep(500)
        this.createLoading = false
      }
    },

    async handleEditGoodsTypeConfirm(e) {
      await this.editGoodsTypeFetcher({ ...e, id: this.currentNode })
      this.refresh()
    },

    async editGoodsTypeFetcher(data) {
      this.createLoading = true
      try {
        await editGoodsType(data)
        this.$message.success('修改成功')
        this.showEditGoodsTypeDialog = false
      } catch (error) {
        this.$message.error(error?.message || '修改失败')
      } finally {
        await sleep(500)
        this.createLoading = false
      }
    },

    async deleteGoodsTypeFetcher(id) {
      try {
        const res = await deleteGoodsType({ id })
        this.$message.success('删除成功')
        await this.refresh()
        this.currentNode = null
      } catch (error) {
        this.$message.error(error?.response?.data?.message || '删除失败')
      }
    },
    // ----------------------------- Goods Type End -----------------------------------

    // ----------------------------- Goods Begin -----------------------------------

    createGoods() {
      this.showDialog = true
    },

    handleEditGoodsType() {
      this.formModelBackup = cloneDeep(this.formModel)
      this.disabled = false
    },

    handleCancel() {
      this.disabled = true
      this.formModel = this.formModelBackup
    },

    async goodsEdit(data) {
      const { name, remark, unit, goods_type_unit, id } = data
      if (this.currentGood === id) return
      this.loading = true
      this.formModelBackup = null
      this.disabled = true

      this.formModel.name = name
      this.formModel.remark = remark
      this.formModel.unit = unit
      this.formModel.unitList = this.auxiliaryUnitFormat(goods_type_unit)
      this.currentGood = id
      await this.sleep(500)
      this.loading = false
    },

    async handleEditConfirm() {
      const flag = await this.$refs.formRef.validate()
      if (!flag) return this.$message.error('请提交正确的信息')
      await this.editGoodsFetcher()
    },

    async editGoodsFetcher() {
      this.btnLoading = true
      try {
        const res = await editWarehouseWarrant({
          ...this.formModel,
          id: this.currentGood,
          unitList: this.formModel.unitList.length > 0
            ? JSON.stringify(this.formModel.unitList) : null
        })
        this.$message.success('修改成功')
        this.refresh()
        this.currentNode = null
        this.currentGood = null
        this.disabled = true
      } catch (error) {
        this.$message.error(error?.response?.data?.message || '修改失败')
      } finally {
        await this.sleep(500)
        this.btnLoading = false
      }
    },

    goodsRemove() {
      this.$confirm(
        '是否删除该项物品？',
        {
          type: 'warning',
          confirmButtonText: '删除',
          cancelButtonText: '取消'
        }
      ).then(() => {
        this.deleteGoodsFetcher(this.currentNode)
      })
    },

    async deleteGoodsFetcher(id) {
      try {
        await deleteWarehouseWarrant(id)
        this.$message.success('删除成功')
        this.currentGood = null
        this.currentNode = null
        this.refresh()
      } catch (error) {
        this.$message.error(error.message || '删除失败')
      }
    },

    async handleConfirm(e) {
      const unitList = Array.isArray(e.unitList) && e.unitList.length > 0
        ? JSON.stringify(e.unitList) : null

      const data = {
        ...e,
        unitList,
        goods_type_id: this.currentNode
      }

      await this.createGoodsFetcher(data)
      this.refresh()
    },

    async createGoodsFetcher(data) {
      this.createLoading = true
      try {
        await createWarehouseWarrant(data)
        this.$message.success('物品录入成功')
        this.showDialog = false
      } catch (error) {
        this.$message.error(error?.response?.data?.message || '物品录入失败')
      } finally {
        await this.sleep(500)
        this.createLoading = false
      }
    },

    handleOpenUnitDialog() {
      this.unitList = cloneDeep(this.formModel.unitList)
      this.showEditUnitDialog = true
    },

    async editUnitConfirm(e) {
      this.formModel.unitList = e
      await this.editGoodsType()
    },

    // ----------------------------- Goods End -----------------------------------

    auxiliaryUnitFormat(list) {
      if (!Array.isArray(list)) return []
      if (list.length <= 0) return []

      return list.map(item => {
        return {
          unit: item?.name,
          conversionRatio: item?.conversion_ratio,
          id: item.id
        }
      })
    },

    sleep(t) {
      return new Promise(resolve => setTimeout(resolve, t))
    },

    refresh() {
      this.getGoodsType()
    }
  }
}
</script>
<style lang="scss" scoped>
.goods-type {
  width: 100%;
  background-color: #fff;
  display: flex;
  &__body {
    width: 100%;
    min-height: 90vh;
    overflow: auto;
    display: flex;
    padding: 20px;
    .left {
      width: 20%;
      height: 100%;

      .custom-tree-node {
        cursor: default;
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 14px;
        padding-right: 8px;
        //display: flex;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        &-button {
          width: 18px;
          height: 18px;
          display: flex;
          justify-content: center;
          align-items: center;
          background: #E8E8E8;
          border-radius: 2px;
          font-size: 12px;
          color: #C0C4CC;
        }

        .type-name {
          width: 100%;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }

      &__add-button {
        margin-top: 20px;
        display: flex;
        justify-content: center;
      }
    }

    .right {
      width: 80%;
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      &__details-content {
        width: 80%;

        .button-group {
          margin-top: 20px;
          //display: flex;
          //justify-content: center;
        }
      }
    }

  }
}

::v-deep(.el-tree-node__content) {
  height: auto;
  padding: 10px;
  border-radius: 4px;
}

::v-deep(.el-tree--highlight-current) {
  .el-tree-node.is-current > .el-tree-node__content {
    background-color: #F5F5F5;
  }
}

.line .el-divider--vertical{
  display:inline-block;
  width:1px;
  height:100%;
  margin:0 20px;
  vertical-align:middle;
  position:relative;
}
</style>
